class Solution(object): def judge(self, p, q): if p == None and q == None: return True if p and q and p.val == q.val: # 如果一边有一边没有那么直接返回False return self.judge(p.left, q.right) and self.judge(p.right, q.left) return False def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if root: return self.judge(root.left, root.right) return True
递归(超简洁版)
运算速度慢
1 2 3 4 5 6 7 8 9 10 11 12
class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def isSym(L,R): if L and R and L.val == R.val: return isSym(L.left, R.right) and isSym(L.right, R.left) return L == R return isSym(root, root)
迭代
换成数组进行判断,运算速度只超过0.5%的人
1 2 3 4 5 6 7 8
class Solution(object): def isSymmetric(self, root): queue = [root] while queue: values = [i.val if i else None for i in queue] if values != values[::-1]: return False queue = [child for i in queue if i for child in (i.left, i.right)] return True